package com.miqtech.master.wyrecorder.ui;

import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.miqtech.master.wyrecorder.BuildConfig;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.annotations.LayoutId;
import com.miqtech.master.wyrecorder.annotations.Title;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.entity.AnchorInfo;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.nim.NIMHelper;
import com.miqtech.master.wyrecorder.user.UserProxy;
import com.miqtech.master.wyrecorder.utils.PreferenceUtils;
import com.miqtech.master.wyrecorder.utils.Utils;
import com.miqtech.master.wyrecorder.utils.imageloader.AsyncImage;
import com.miqtech.master.wyrecorder.widget.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by arvin on 2016/10/28.
 */
@LayoutId(R.layout.activity_anchorhome)
@Title(title = "我的信息")
public class AnchorHomeActivity extends BaseAppCompatActivity {
    @BindView(R.id.img_head)
    CircleImageView imgHead;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvSex)
    TextView tvSex;

    @BindView(R.id.rlHostSetting)
    RelativeLayout rlHostSetting;
    @BindView(R.id.spinner_url)
    Spinner spinnerUrl;
    @BindView(R.id.tvLiveRoom)
    TextView tvLiveRoom;
    @BindView(R.id.tvLiveTime)
    TextView tvLiveTime;
    @BindView(R.id.tvMobile)
    TextView tvMobile;
    @BindView(R.id.tvReceiveYubi)
    TextView tvReceiveYubi;
    @BindView(R.id.tvReceiveYuer)
    TextView tvReceiveYuer;
    @BindView(R.id.tvTimeUnit)
    TextView tvTimeUnit;

    private AnchorInfo anchorInfo;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        getAnchorDataRequet();
        showUserInfo();
    }

    private void showUserInfo() {
        User user = UserProxy.getUser();
        if(user !=null) {
            AsyncImage.displayImage(user.getIcon(), imgHead,R.drawable.default_head);
            tvName.setText(user.getNickname());
            if (user.getSex() == 0) {
                tvSex.setText("男");
                Drawable d = new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.home_male_label));
                d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight());
                tvSex.setCompoundDrawables(d, null, null, null);
            } else {
                tvSex.setText("女");
                Drawable d = new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.home_female_label));
                d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight());
                tvSex.setCompoundDrawables(d, null, null, null);
            }
            tvMobile.setText("" + user.getMobile());
            tvLiveRoom.setText(user.getRoomNumber());
            tvLiveTime.setText(user.getNickname());
        }
        showHostSetting();
    }

    @OnClick({R.id.btnLogout})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogout:
                logout();
                break;
        }
    }

    private void logout() {
        UserProxy.setUser(null);
        cleanUser();
        NIMHelper.getInstance().logout();
        finish();
        jumpToActivity(LoginActivity.class);
    }

    private void cleanUser() {
        PreferenceUtils.putString("user", "");
        PreferenceUtils.putString("password", "");
    }

    private void showHostSetting() {
        if (BuildConfig.DEBUG) {
            rlHostSetting.setVisibility(View.VISIBLE);
            final String[] urls = getResources().getStringArray(R.array.host);
            spinnerUrl.setAdapter(new ArrayAdapter<String>(this, R.layout.layout_host_simple, urls));
            spinnerUrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    API.HOST = urls[position];
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            int selection = 0;
            for (int i = 0; i < urls.length; i++) {
                if (urls[i].equals(API.HOST)) {
                    selection = i;
                }
            }
            spinnerUrl.setSelection(selection);
        } else {
            rlHostSetting.setVisibility(View.GONE);
        }
    }

    private void getAnchorDataRequet() {
        Map<String, String> map = new HashMap<>();
        User user = UserProxy.getUser();
        if (user != null) {
            map.put("userId", user.getId());
            map.put("token", user.getToken());
        }
        sendHttpRequest(API.MY_LIVE, map);
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        try {
            switch (method) {
                case API.MY_LIVE:
                    analyzeData(object);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析数据
     *
     * @param js
     */
    private void analyzeData(JSONObject js) {
        try {
            if ("0".equals(js.getString("code")) && js.has("object")) {
                Gson gson = new Gson();
                anchorInfo = gson.fromJson(js.getJSONObject("object").toString(), AnchorInfo.class);
                updateAnthor(anchorInfo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void updateAnthor(AnchorInfo anchorInfo) {
        tvReceiveYubi.setText(Utils.formatString(anchorInfo.getYuerCoin()));
        tvReceiveYuer.setText(Utils.formatString(anchorInfo.getBait()));
        setLiveTime(anchorInfo.getDuration());
    }

    private void setLiveTime(int liveTime) {
       /* int time = 0;
        boolean isShowHour = false;
        if (liveTime > 60) {
            time = liveTime / 60;
            isShowHour = true;
        } else {
            time = liveTime;
            isShowHour = false;
        }*/
        tvLiveTime.setText("" + liveTime);
        if (true) {
            tvTimeUnit.setText("小时");
        } else {
            tvTimeUnit.setText("分钟");
        }

    }
}
